#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""这个模块属于多余模块，具体发帖工作应该交给tbitem,JD_utils.wade_Accounts来操作"""
import logging
import random
from tbitem import models
from tbitem.JD_utils.wade_Spider_Tool2 import JDSpider
from tbitem.util.BaseUtil import BaseArticle

from tbitem.util.maokoulingAccunt import maokouling_Accunt
from tbitem.util.postDiscuz import postDiscuzBBs

server_logger = logging.getLogger("server")
import time
from BaseWeb import models as BaseWeb_models
from tbitem.util import maokoulingClass, BaseUtil

from tbitem.util.itemTemplate import ContentFactory_forDiscuz, ContentFactory_forDjango
from tbitem.util.qiboPOST import bokeePOST, ContentConfig
import os, django

'''各种发帖的系统流程函数'''


# 通过链接发京东到discuz 数码之家
def postDISCUZ_By_FakeUrl(pages=5,username='怎么样评测'):
    '''运行流程：传入id，论坛用户名，标题就会自动发帖'''
    '''先解析别人的链接，分析出id'''
    '''1、jdSpider（）爬虫获得原始评论和图列表'''
    '''2、创建BaseArticle类实例对象wadeOBJCET'''
    '''3、wadeOBJCET调用论坛模板，产出发布内容'''
    '''4、根据id和账号信息换出商品链接和店铺链接'''
    '''4、引入postDiscuzBBs（）进行发布'''

    # 输入标题、id、用户名
    '''#发帖信息初始化'''
    discuz_Account = models.DiscuzAccount.objects.filter(username=username).first()
    maoAccount = maokouling_Accunt(apkey=discuz_Account.apkey, key_id=discuz_Account.JDkey_id)
    dbdata = models.Jdong.objects.filter(hasPOst=False).first()  # 取数据库中一条可用数据
    if not discuz_Account:
        return False






    # 运行必须的参数：长连接 短链接 评论 图片列表 jdid, shopid, shopname, skuName, item_MainImg, item_price
    fid = discuz_Account.fid  # 板块编号
    username = discuz_Account.username  # 发帖用户名
    url = discuz_Account.postUrl  # 发帖地址
    shotUrl, longUrl = maoAccount.getLongUrl_By_FakeUrl(dbdata.FakeURL)
    jdid, shopid, shopname, skuName, item_MainImg, item_price = maoAccount.getjdid(shotUrl)
    if jdid == []:
        dbdata.hasPOst = True
        dbdata.save()
        return False


    print('获取原始评论')
    commentList, imgList = jdSpider(jdid, pages)  # 京东爬虫

    print('开始配置模板')
    wadeOBJCET = BaseArticle(dbdata.title, commentList, imgList, '', 'www.url.com')
    content, pinglunList = wadeOBJCET.templateFactory_forDiscuz(jdid, shopid, shopname, skuName, item_MainImg,item_price, shotUrl, longUrl)  # 主贴内容 and 评论楼层

    # 调用论坛发帖模块函数块需要的内容----START
    postresult = postDiscuzBBs(dbdata.title, content,pinglunList, fid, username, url)
    del content, pinglunList, commentList, imgList
    # 调用论坛发帖模块函数块需要的内容----End

    if postresult == True:
        print(f"{discuz_Account.discuzName}发帖成功")
        # 保存数据库发帖状态
        dbdata.hasPOst = True
        dbdata.save()
        return True
    else:
        return False



# 通过链接发京东到discuz 手电大家谈
def postDISCUZ_By_shoudianUrl(pages=5,username='怎么样评测'):
    '''运行流程：传入id，论坛用户名，标题就会自动发帖'''
    '''先解析别人的链接，分析出id'''
    '''1、jdSpider（）爬虫获得原始评论和图列表'''
    '''2、创建BaseArticle类实例对象wadeOBJCET'''
    '''3、wadeOBJCET调用论坛模板，产出发布内容'''
    '''4、根据id和账号信息换出商品链接和店铺链接'''
    '''4、引入postDiscuzBBs（）进行发布'''

    # 输入标题、id、用户名
    '''#发帖信息初始化'''







# 通过链接发京东到Qb
def postQiBo_By_FakeUrl(username='怎么样评测', pages=5):
    # 引入博客账户    引入基础bbs账户,两个账户进行关联  引入猫口令 初始化操作
    bokeeconfig = ContentConfig()
    bokeeAccunt = bokeeconfig.getACCOUNT(username)
    discuz_Account = models.DiscuzAccount.objects.filter(pk=bokeeAccunt.qibo_Fk_Discuz_id).all().first()
    maoAccount = maokouling_Accunt(apkey=discuz_Account.apkey, key_id=discuz_Account.JDkey_id)
    dbdata = models.Jdong.objects.filter(hasPOst=False).first()  # 取数据库中一条可用数据
    if not (discuz_Account or bokeeAccunt):
        print(discuz_Account,maoAccount,dbdata)
        server_logger.error(f"{time.strftime('%H:%M:%S')}-if not discuz_Account or bokeeAccunt::{discuz_Account,maoAccount,dbdata}")
        return False


    # 运行必须的参数：长连接 短链接 评论 图片列表 jdid, shopid, shopname, skuName, item_MainImg, item_price
    shotUrl, longUrl = maoAccount.getLongUrl_By_FakeUrl(dbdata.FakeURL)
    jdid, shopid, shopname, skuName, item_MainImg, item_price = maoAccount.getjdid(shotUrl)
    if jdid==[]:
        dbdata.hasPOst = True
        dbdata.save()
        server_logger.error(f"jdid==[]")

        return False

    #获取原始评论
    commentList, imgList = JDSpider().spider_comment(jdid, pages)  # 京东爬虫

    print(f'开始配置模板,评论列表{len(commentList)},图片列表{len(imgList)}')
    # 创造模板使用对象  进行模板化处理
    wadeOBJCET = BaseArticle(dbdata.title, commentList, imgList, '', 'www.url.com')
    content = wadeOBJCET.templateFactory_forQb(jdid, shopid, shopname, skuName, item_MainImg, item_price, shotUrl,
                                               longUrl)  # 主贴内容 and 评论楼层
    if len(content)>=100:
        print('内容生产成功')
    else:
        print('内容生产失败')
        server_logger.error(f"len(content)>=100，内容生产问题")
        return False


    # 调用企业博客发帖模块函数块需要的内容----START
    bokeeAccunt.title = dbdata.title
    bokeeAccunt.content = content
    postresult = bokeePOST(bokeeAccunt)
    del content, commentList, imgList
    # 调用企业博客发帖模块函数块需要的内容----END


    if postresult == True:
        print(f"{bokeeAccunt}发帖成功")
        # 保存数据库发帖状态
        dbdata.hasPOst = True
        dbdata.save()
        return True
    else:
        server_logger.error(f"postresult = bokeePOST(bokeeAccunt)出错")

        return False
